<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="business/layout">
<head>
<meta charset="utf-8" />
<title>天天点餐</title>
</head>
<body class="no-skin">
	<div layout:fragment="content">
		<div class="main-inner">
			<div class="container">
				<div class="span12">
					<div class="info-box">
						<div th:if="${file} != null">
							<script type="text/javascript">
								alert('图片格式不正确');
							</script>
						</div>
						<a class="button button-block button-rounded button-action button-large add-food">增添菜品</a>
						<table id="showTable" class="table table-striped table-bordered table-hover">
							<thead>
								<tr>
									<th>菜系</th>
									<th>菜名</th>
									<th>价格</th>
									<th>会员价</th>
									<th>图片</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
							</tbody>
						</table>
						<div class="panel col-sm-10 panel-default">
        			<div class="panel-body reply-top media">
            			<div id="page"></div>
        			</div>
    			</div>
					</div>
				</div>
			</div>
		</div>
		<!-- /container -->
		<!-- /main-inner -->

		<div class="modal hide" id="addFoodModal" tabindex="-1" role="dialog"
			aria-labelledby="addFoodModallabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
						<h4 class="modal-title" id="addFoodModallabel">添加菜品</h4>
					</div>
					<div class="modal-body">
					<form id="addFoodForm" action="/food/addFood" method="POST" enctype="multipart/form-data">
							<div class="form-group">
								<select name="foodType" id="foodType"></select>
							</div>
							<div class="form-group">
								菜品名：<input type="text" id="foodName" name="foodName" />
							</div>
							<div class="form-group">
								描述：<textarea id="describe" name="describe" ></textarea>
							</div>
							<div class="form-group">
								价格：<input type="text" id="price" name="price" />
							</div>
							<div class="form-group">
								会员价：<input type="text" id="mPrice" name="mPrice" />
							</div>
							<div class="form-group">
								图片：<input type="file" id="image" name="image" />
							</div>
							<img id="preview" class="food-image" />
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						<button id="addFoodSaveBtn" type="button" class="btn btn-primary">保存</button>
					</div>
				</div>
			</div>
		</div>
		
		<div class="modal hide" id="updateFoodModal" tabindex="-1" role="dialog"
			aria-labelledby="updateFoodModallabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
						<h4 class="modal-title" id="updateFoodModallabel">修改菜品</h4>
					</div>
					<div class="modal-body">
					<form id="updateFoodForm" action="/food/updateFood" method="POST" enctype="multipart/form-data">
							<div class="form-group">
								<input name="id" class="hidden"/>
								<select name="foodType" id="foodType"></select>
							</div>
							<div class="form-group">
								菜品名：<input type="text" id="foodName" name="foodName" />
							</div>
							<div class="form-group">
								描述：<textarea id="describe" name="describe" ></textarea>
							</div>
							<div class="form-group">
								价格：<input class="priceFormat" type="text" id="price" name="price" />
							</div>
							<div class="form-group">
								会员格：<input type="text" id="mPrice" name="mPrice" />
							</div>
							<div class="form-group">
								图片：<input type="file" id="image" name="image" />
							</div>
							<img id="preview" class="food-image" />
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						<button id="updateFoodSaveBtn" type="button" class="btn btn-primary">保存</button>
					</div>
				</div>
			</div>
		</div>
		
		<script type="text/javascript" th:src="@{/js/jquery.metadata.js}"></script>
		<script type="text/javascript" th:src="@{/js/jquery.validate.min.js}"></script>
		<script type="text/javascript" th:src="@{/js/messages_zh.js}"></script>
		<script type="text/javascript" th:src="@{/js/ajaxfileupload.js}"></script>
		<script type="text/javascript">
			/*<![CDATA[*/
			$(document).ready(function() {
				
				pagehtml();
				
				$('.add-food').click(function() {
					$.ajax({
						type: "POST",
						url: "/food/getAllFoodType",
						dataType: "json",
						success: function(data){
							var foodType = '';
							$('#addFoodForm #foodType').html(foodType);
							for(var i = 0; i < data.length;i++){
								foodType += '<option value="'+data[i].id+'">'+data[i].typeName +'</option>';
							}
							$('#addFoodForm #foodType').append(foodType);
							$('#addFoodModal').modal('show');
						}
					});
				});
				
				//提交保存
				$('#addFoodSaveBtn').click(function(){
					if($('#addFoodForm').valid()){
						var price = parseFloat($('#addFoodForm input[name="price"]').val());;
						var mprice = parseFloat($('#addFoodForm input[name="mPrice"]').val());
						if(price >= mprice){
						$('#addFoodForm').submit();
						} else {
							alert('会员价不能高于价格');	
						}
					} 
				});
				
				$('#updateFoodSaveBtn').click(function(){
					if($('#updateFoodForm').valid()){
						var price = parseFloat($('#updateFoodForm input[name="price"]').val());
						var mprice = parseFloat($('#updateFoodForm input[name="mPrice"]').val());
						if(price >= mprice){
							$('#updateFoodForm').submit();
						} else {
							alert('会员价不能高于价格');	
						}
					}
				});
				
				$.ajax({
					type: "POST",
					url: "/food/getAllFoodType",
					dataType: "json",
					success: function(data){
						var foodType = '';
						for(var i = 0; i < data.length;i++){
							foodType += '<option value="'+data[i].id+'">'+data[i].typeName +'</option>';
						}
						$('#updateFoodForm #foodType').append(foodType);
					}
				});
				
				//弹出修改模态框
				$('body').delegate('.update-food','click',function(){
					var id = $(this).val();
					$.ajax({
						type: "POST",
						url: "/food/getFoodById",
						data: {id : id},
						dataType: "json",
						success: function(data){
							var foodTypes = $('#updateFoodForm #foodType option');
							//设置菜色的菜品
							for(var i = 0;i < foodTypes.length; i++){
								if(data.foodTypeId == foodTypes[i].value){
									foodTypes[i].selected = true;
								}
							}
							$('#updateFoodForm input[name="id"]').val(id);
							$('#updateFoodForm input[name="foodName"]').val(data.foodName);
							$('#updateFoodForm textarea').val(data.remark);
							$('#updateFoodForm input[name="price"]').val(data.price);
							$('#updateFoodForm input[name="mPrice"]').val(data.mPrice);
							$('#updateFoodForm #preview').attr('src', "/food/getImage?image="+data.image);
							$('#updateFoodModal').modal('show');
						}
					});
				});
			});
			
			function del(){
				var msg = "您真的确定要删除吗？\n\n请确认！";
				if(confirm(msg)){
					return true;
				}else{
					return false;
				}
			}
			
			function pagehtml(pageNum) {
			    if (pageNum == null){
			        pageNum=1;
			    } else {
			        pageNum=pageNum;
			    }
			    $.ajax({
			        url:"/food/findAllFoods",
			        type:"post",
			        dataType:"json",
			        data: {pageNum : pageNum, pageSize : 3},
			        success:function (data) {
			            var options = {
			                alignment:"center",//居中显示
			　　　　　　　　　　currentPage: data.pageNum,//当前页数
			　　　　　　　　　　totalPages: data.pages,//总页数 注意不是总条数
			　　　　　　　　　　pageUrl: function(type, page, current){
			                    if (page==current) {
			                        return "javascript:void(0)";
			                    } else {
			                        return "javascript:pagehtml("+page+")";
			                    }
			                }
			            };
			            var html = "";
			            $.each(data.list, function (i, obj) {
			            	var price = parseFloat(obj.price);
			            	var mPrice = parseFloat(obj.mPrice);
			            	var prices = '';
			            	var mPrices = '';
			            	if(price > 1000.00){
			            		prices += parseInt((price / 1000));
			            		prices += ',';
			            		prices += ((price % 1000).toFixed(2));
			            	}
			            	if(mPrice > 1000.00){
			            		mPrices += parseInt((mPrice / 1000));
			            		mPrices += ',';
			            		mPrices += ((mPrice % 1000).toFixed(2));
			            	}
			            	if(prices == ''){
			            		prices = price;
			            	}
			            	if(mPrices == '') {
			            		mPrices = mPrice;
			            	}
			                html += '<tr>';
			            	html += '<td>'+ obj.foodTypeName +'</td>';
			                html += '<td>'+ obj.foodName +'</td>';
			                html += '<td>'+ prices +'</td>';
			                html += '<td>'+ mPrices +'</td>';
			                if(obj.image != null && obj.image != ""){
			                	html += '<td><img alt="图片" src=/food/getImage?image='+ obj.image +' class="food-image"></img></td>';
			                } else {
			                	html += '<td><label>无图片</label></td>';
			                }
							html += '<td><button type="button" class="btn btn-success update-food" value='+ obj.id +'>修改</button>';
							html += '<a onclick="return del()" href=/food/deleteFoodById/'+ obj.id +' class="btn btn-danger delete-food">删除</a></td>';
			                html += '</tr>';
			            });
			            $("#showTable tbody").empty();
			            $("#showTable tbody").append(html);
			            $("#page").bootstrapPaginator(options);
			        },
			        error:function (error) {
			            alert("error");
			        }
			    });
			}
			/*]]>*/
		</script>
		<script>
			/* 添加图片后显示图片  */
			/* <![CDATA[ */
		$().ready(function(){
			$(function() {
				$('#addFoodForm input[name="image"]').change(
								function() {
									var $file = $(this);
									var fileObj = $file[0];
									var windowURL = window.URL
											|| window.webkitURL;
									var dataURL;
									var $img = $("#addFoodForm #preview");

									if (fileObj && fileObj.files
											&& fileObj.files[0]) {
										dataURL = windowURL
												.createObjectURL(fileObj.files[0]);
										$img.attr('src', dataURL);
									} else {
										dataURL = $file.val();
										var imgObj = document
												.getElementById("preview");
										// 两个坑:
										// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
										// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
										imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
										imgObj.filters
												.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
									}
								});
			});
		});
		$().ready(function(){
			$(function() {
				$('#updateFoodForm input[name="image"]').change(
								function() {
									var $file = $(this);
									var fileObj = $file[0];
									var windowURL = window.URL
											|| window.webkitURL;
									var dataURL;
									$('#brose').hide();
									var $img = $("#updateFoodForm #preview");
									
									if (fileObj && fileObj.files
											&& fileObj.files[0]) {
										dataURL = windowURL
												.createObjectURL(fileObj.files[0]);
										$img.attr('src', dataURL);
									} else {
										dataURL = $file.val();
										var imgObj = document
												.getElementById("preview");
										// 两个坑:
										// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
										// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
										imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
										imgObj.filters
												.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
									}
								});
			});
		});
			/* ]]> */
		</script>
		<script th:inline="javascript">
		/*<![CDATA[*/
			var message = [[${message}]];
			if(message != null){
				alert(message);
			}
		/*]]>*/
		</script>
		<script type="text/javascript">
		$().ready(function() {
			$.validator.addMethod("priceFormat",function(value,element){
                var score = /^([1-9]\,)?\d{0,3}\.\d{2}$/;
                return this.optional(element) || (score.test(value));
            },"价格格式：9,999.99");
			$('#addFoodForm').validate({
				rules : {
					foodName : {
						required : true,
						maxlength : 20
					},
					describe : {
						maxlength : 200
					},
					price : {
						required : true ,
						priceFormat : true
					},
					mPrice : {
						required : true,
						priceFormat : true 
					}
				},
			});
			$('#updateFoodForm').validate({
				rules : {
					foodName : {
						required : true,
						maxlength : 20
					},
					describe : {
						maxlength : 200
					},
					price : {
						required : true ,
						priceFormat : true
					},
					mPrice : {
						required : true,
						priceFormat : true 
					}
				},
			});
		});
	</script>
	<script type="text/javascript" th:src="@{/js/jquery.metadata.js}"></script>
	<script type="text/javascript" th:src="@{/js/jquery.validate.min.js}"></script>
	<script type="text/javascript" th:src="@{/js/messages_zh.js}"></script>
	</div>
</body>
</html>
